export class CoreStorage {
    constructor(public key = 'g') {}

    setKey(k: string) {
        this.key = k;
    }

    getKey(k: string) {
        return `@@${this.key}-${k}@@`;
    }

    apt = localStorage;
    setApt(apt: Storage) {
        this.apt = apt;
    }

    get(key: string) {
        try {
            const pre = this.apt.getItem(this.getKey(key)) || '';
            return JSON.parse(pre).value;
        } catch (err) {
            return null;
        }
    }

    set(key: string, v: any) {
        return this.apt.setItem(
            this.getKey(key),
            JSON.stringify({
                date: Date.now(),
                value: v,
            }),
        );
    }

    remove(key: string) {
        this.apt.removeItem(this.getKey(key));
    }

    clear() {
        Object.keys(this.apt).forEach((key) => {
            if (key.match(`@@${this.key}-`)) {
                this.apt.removeItem(key);
            }
        });
    }
}

export class CoreStorageAsync {
    constructor(public key = 'g') {}

    setKey(k: string) {
        this.key = k;
    }

    getKey(k: string) {
        return `@@${this.key}-${k}@@`;
    }

    apt = localStorage;
    setApt(apt: Storage) {
        this.apt = apt;
    }

    get(key: string) {
        return Promise.resolve(this.apt.getItem(this.getKey(key))).then((r: any) => {
            try {
                if (typeof r === 'string') return JSON.parse(r).value;
                return r.value;
            } catch (err) {
                return null;
            }
        });
    }

    set(key: string, v: any) {
        return Promise.resolve(
            this.apt.setItem(
                this.getKey(key),
                JSON.stringify({
                    date: Date.now(),
                    value: v,
                }),
            ),
        );
    }

    remove(key:string) {
        return Promise.resolve(this.apt.removeItem(this.getKey(key)));
    }

    clear() {
        return Promise.resolve(this.apt.clear());
    }
}
